// b09.v
// Verilog version, rewritten by Li Shen, Aug 2002
// Institute of Computing Technology, Chinese Academy of Sciences
// The original VHDL version is b09.vhd from Politecnico di Torino

module b09 (clock, reset, x, y);
input clock;
input reset;
input x;
output y;
/////
wire clock;
wire reset;
wire x;
reg y;
/////
parameter Bit_start=1, Bit_stop=0, Bit_idle=0;
parameter Zero_8=8'b00000000, Zero_9=9'b000000000;
parameter INIT = 0, RECEIVE = 1, EXECUTE = 2, LOAD_OLD = 3;
reg [8:0] d_in;          
reg [7:0] d_out, old;
reg [1:0] stato;
/////
always @(posedge clock)
begin
  if (reset)
  begin
    	stato = INIT;
    	d_in <= Zero_9;   
    	d_out <= Zero_8;  
   	old <= Zero_8;  
   	y <= Bit_idle;  
  end
  else
    case (stato)

    INIT:
    begin
	stato = RECEIVE;
	d_in <= Zero_9;   
	d_out <= Zero_8;  
	old <= Zero_8;  
	y <= Bit_idle;  
    end

    RECEIVE:
	if (d_in[0] == Bit_start)
	begin
	  old <= d_in[8:1];  
	  y <= Bit_start;
	  d_out <= d_in[8:1];
	  d_in <= Bit_start<<8 | Zero_8;
	  stato = EXECUTE;
	end
	else
	begin
	  d_in <= {x , d_in[8:1]};
	  stato = RECEIVE;
	end

    EXECUTE :
    begin 
	if (d_in[0] == Bit_start)
	begin
	  y <= Bit_stop;
	  stato = LOAD_OLD;
	end
	else
	begin
	  d_out <= Bit_idle<<7 | d_out[7:1];
	  y <= d_out[0];
	  stato = EXECUTE;
	end
	d_in <= {x , d_in[8:1]};
    end

    LOAD_OLD:
	if (d_in[0] == Bit_start)
	begin 
	  if (d_in[8:1] == old)
	  begin
	    d_in <= Zero_9;
	    y <= Bit_idle;
	    stato = LOAD_OLD;
	  end
	  else
	  begin
	    y <= Bit_start;
	    d_out <= d_in[8:1];
	    d_in <= Bit_start<<8 | Zero_8;
	    stato = EXECUTE;
	  end
	  old <= d_in[8:1];
	end
	else
	begin
	  d_in <= {x , d_in[8:1]};
	  y <= Bit_idle;   
	  stato = LOAD_OLD;
	end
	
    endcase
end
endmodule
